<template>
	<view>
		<view class="w-full text-center">
			<text class="">注册</text>
		</view>
		<view class="p-4">
			<view>
				<uv-form ref="formRef" :model="entity" :rules="rules" labelPosition="left" labelWidth="5rem">
					<uv-form-item label="用户名" prop="username" borderBottom>
						<uv-input v-model="entity.username" border="none">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="密码" prop="password" borderBottom>
						<uv-input v-model="entity.password" type="password" border="none">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="确认密码" prop="confirmPassword" borderBottom>
						<uv-input v-model="entity.confirmPassword" type="password" border="none">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="手机号" prop="phone" borderBottom>
						<uv-input v-model="entity.phone" border="none">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="邮箱" prop="email" borderBottom>
						<uv-input v-model="entity.email" border="none">
						</uv-input>
					</uv-form-item>
					<uv-form-item label="验证码" prop="verifyCode" borderBottom>
						<uv-input v-model="entity.verifyCode" border="none">
							<template v-slot:suffix>
								<image :src="verifyCodeUrl" class="w-[120px] h-[40px]" @click="updateVerifyCode"></image>
							</template>
						</uv-input>
					</uv-form-item>
					<uv-form-item>
						<uv-button type="primary" text="注册" @click="register"></uv-button>
					</uv-form-item>
					<uv-form-item>
						<uv-button text="已有账号，返回登录" @click="login"></uv-button>
					</uv-form-item>
				</uv-form>
			</view>
		</view>
		<view>
			<uv-notify ref="notify"></uv-notify>
		</view>
	</view>
</template>

<script setup>
import { onBeforeUnmount, onMounted, reactive, ref, getCurrentInstance } from 'vue';
import authService from "@/services/auth.service";
import { REGEX_PASSWORD, REGEX_EMAIL, REGEX_PHONE } from "@/utils/regexes";
import { onLoad } from "@dcloudio/uni-app";

const entity = ref({
	username: '',
	password: '',
	confirmPassword: '',
	phone: '',
	email: '',
	verifyCode: '',
});
const verifyCodeUrl = ref("");
const formRef = ref();
const loading = ref(false);

const notify = ref();
const notifyConfig = ref({
	text: '',
	type: '',
});

const rules = reactive({
	username: [
		{
			required: true,
			message: '请输入用户名',
			trigger: ['blur', 'change'],
		},
		{
			asyncValidator: async (rule, value, callback) => {
				if (!value) {
					callback();
					return;
				}
				const res = await authService.checkUsername(value);
				if (!res.data.data) {
					callback(new Error("用户名已存在"));
					return;
				}
				callback();
			},
			trigger: ['blur'],
		}
	],
	password: [
		{
			required: true,
			message: '请输入密码',
			trigger: ['blur', 'change'],
		},
		{
			validator: (rule, value, callback) => {
				return REGEX_PASSWORD.test(value);
			},
			message: "密码格式应为8-18位数字、字母、符号的任意两种组合",
			trigger: ['blur'],
		},
	],
	confirmPassword: [
		{
			required: true,
			message: '请输入确认密码',
			trigger: ['blur', 'change'],
		},
		{
			validator: (rule, value, callback) => {
				if (entity.value.password && entity.value.confirmPassword && entity.value.password != entity.value.confirmPassword) {
					return false;
				}
				return true;
			},
			message: "两次密码输入不一致",
			trigger: ['blur'],
		}
	],
	phone: [
		{
			required: true,
			message: '请输入手机号',
			trigger: ['blur', 'change'],
		},
		{
			validator: (rule, value, callback) => {
				return REGEX_PHONE.test(value);
			},
			message: "手机号格式不正确",
			trigger: ['blur'],
		},
		{
			asyncValidator: async (rule, value, callback) => {
				if (!value) {
					callback();
					return;
				}
				const res = await authService.checkPhone(value);
				if (!res.data.data) {
					callback(new Error("手机号已存在"));
					return;
				}
				callback();
			},
			trigger: ['blur'],
		}
	],
	email: [
		{
			required: true,
			message: '请输入邮箱',
			trigger: ['blur', 'change'],
		},
		{
			validator: (rule, value, callback) => {
				return REGEX_EMAIL.test(value);
			},
			message: "邮箱格式不正确",
			trigger: ['blur'],
		},
		{
			asyncValidator: async (rule, value, callback) => {
				if (!value) {
					callback();
					return;
				}
				const res = await authService.checkEmail(value);
				if (!res.data.data) {
					callback(new Error("邮箱已存在"));
					return;
				}
				callback();
			},
			trigger: ['blur'],
		}
	],
	verifyCode: [
		{
			required: true,
			message: '请输入验证码',
			trigger: ['blur', 'change'],
		},
	],
});

onLoad(async () => {
	updateVerifyCode();

	load();
});

const updateVerifyCode = async () => {
	const res = await authService.getVerifyCode();
	verifyCodeUrl.value = `${res.data.data?.image}`;
	entity.value.verifyCodeKey = res.data.data?.key;
}

const load = async () => {

}

const showNotify = (config) => {
	notifyConfig.value = config;
	notify.value.show({
		type: config.type,
		message: config.message,
	});
}

const showError = (message) => {
	showNotify({ message: message, type: "error" });
}

const login = async () => {
	uni.navigateTo({
		url: "/pages/login/login",
	})
};

const register = async () => {
	const formEl = formRef.value;
	loading.value = true;
	if (!formEl) {
		loading.value = false;
		return;
	}
	try {
		await formEl.validate();

		const res = await authService.register(entity.value);
		showNotify({ message: "注册成功", type: "success" });
		uni.navigateTo({
			url: "/pages/login/login",
		});
	} catch (err) {
		if (err.data && err.data.message) {
			showError(err.data && err.data.message);
		}

		updateVerifyCode();
		throw err;
	} finally {
		loading.value = false;
	}
}
</script>

<style lang="scss"></style>